package server.database;

/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 * DatabaseConnection.java
 *
 * Steven Louie Apr. 8, 2012
 * 
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import server.constants.ServerProperties;

public class DatabaseConnection {

    private static ThreadLocal<Connection> con = new ThreadLocalConnection();
    private final static String dbUsername = ServerProperties.dbUsername;
    private final static String dbPassword = ServerProperties.dbPassword;

    public static Connection getConnection() {
        return con.get();
    }

    public static void closeAll() throws SQLException {
        for (Connection conn : ThreadLocalConnection.allConnections) {
            conn.close();
        }
    }

    private static class ThreadLocalConnection extends ThreadLocal<Connection> {

        public static Collection<Connection> allConnections = new LinkedList<>();

        @Override
        protected Connection initialValue() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
            Connection con;
            try {
                con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/actino?autoReconnect=true", dbUsername, dbPassword);
                allConnections.add(con);
                return con;
            } catch (SQLException ex) {
                Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }
    }
}
